package gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

import todo.MyTask;
import todo.TaskSet;
import tools.OptionReader;
import calendar.Event;
import calendar.EventSet;
import contacts.PersonSet;

/**
 * Klasse repräsentiert die Wochenansicht des Kalenders
 * 
 * @author Michi
 * 
 */
public class WeekView extends JPanel {

	/**
	 * Member Data
	 */
	private static final long serialVersionUID = 5823452809869954480L;
	private Test mainInstance;
	private WeekView ownInstance;
	private TaskSet ts;
	private PersonSet ps;
	private EventSet es;
	// muss generisch bleiben um verschiedene Datentypen speichern zu können!!
	@SuppressWarnings("rawtypes")
	private List allCalendarItems;
	private int counter = 0;
	private Date clickedDay;
	private JScrollPane weekPanelScrollPane;
	private JPanel weekPanel;
	private JTextField wochenInfoTextField;
	private JPanel buttonPanel;
	private OptionReader or;
	private String[] windowColorsSeperated;
	private int r;
	private int g;
	private int b;

	// Sprachen (0 = deutsch; 1 = englisch; 2 = latein)
	int speak = 0;

	String[] monatsansicht = { "Monatsansicht", "Month View", "Camp Totus" };
	String[] jahreKlammer = { " Jahre)", " years)", " annalis)" };

	String[] toolTipLM = { "Zeigt die vorherige Woche an.",
			"Show the last week.", "Ostendit priore hebdomada." };
	String[] toolTipNM = { "Zeigt die nächste Woche an.",
			"Show the next week.", "Ostendit proximo hebdomada." };
	String[] toolTipAM = { "Hier wird Ihnen die aktuelle Woche dargestellt.",
			"Here you can see the current week.",
			"Hic vos ero ostendo occurrenti hebdomada." };
	String[] addEvent = { "Hier können sie einen neuen Termin hinzufügen",
			"Add a new event", "Hic adere nuovus terminus" };

	String[] kalender = { "Kalender", "Calendar", "Calendarium" };
	String[] kontakte = { "Kontakte", "Contacts", "Contactus" };
	String[] todo = { "Aufgabe", "Task", "Negotium" };
	String[] mail = { "E-Mail", "Mail", "Littersa" };
	private JButton btnNewButton;
	private JButton btnNewButton_1;
	private JButton btnNewButton_2;
	private JButton btnNewButton_3;
	private JButton btnNewButton_4;

	/**
	 * Create the panel.
	 */
	@SuppressWarnings({ "rawtypes" })
	public WeekView(final Test test, Date d) {// TODO

		// Initialisierung

		setOwnInstance(this);
		mainInstance = test;
		allCalendarItems = new ArrayList();
		ts = new TaskSet();
		ps = new PersonSet();
		es = new EventSet();
		clickedDay = d;
		or = new OptionReader();
		try {
			or.getOpionsFromFile();
		} catch (IOException e2) {

			e2.printStackTrace();
		}

		String windowColors = or.getColorSetting();
		windowColorsSeperated = windowColors.split(",");
		r = Integer.parseInt(windowColorsSeperated[0]);
		g = Integer.parseInt(windowColorsSeperated[1]);
		b = Integer.parseInt(windowColorsSeperated[2]);

		speak = Integer.parseInt(or.getLanguage());

		setBackground(Color.GRAY);
		setLayout(new BorderLayout(0, 0));

		// ---------------------------BeginnButtonPanel---------------------------
		buttonPanel = new JPanel();
		buttonPanel.setBackground(new Color(r, g, b));
		buttonPanel.setMaximumSize(new Dimension(32767, 40));
		buttonPanel.setMinimumSize(new Dimension(10, 40));
		buttonPanel.setPreferredSize(new Dimension(10, 40));
		add(buttonPanel, BorderLayout.NORTH);
		GridBagLayout gbl_buttonPanel = new GridBagLayout();
		gbl_buttonPanel.columnWidths = new int[] { 80, 110, 140, 0, 0, 0, 0 };
		gbl_buttonPanel.rowHeights = new int[] { 0, 0 };
		gbl_buttonPanel.columnWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 1.0,
				0.0, Double.MIN_VALUE };
		gbl_buttonPanel.rowWeights = new double[] { 0.0, Double.MIN_VALUE };
		buttonPanel.setLayout(gbl_buttonPanel);

		Icon iconNeu = new ImageIcon("src/pictures/add.png");
		btnNewButton = new JButton(iconNeu);
		btnNewButton.setToolTipText(addEvent[speak]);
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				new NewEventWindow(getClickedDay(), getOwnInstance())
						.setVisible(true);
			}
		});
		btnNewButton.setMaximumSize(new Dimension(80, 40));
		btnNewButton.setMinimumSize(new Dimension(40, 40));
		btnNewButton.setPreferredSize(new Dimension(40, 40));
		GridBagConstraints gbc_btnNewButton = new GridBagConstraints();
		gbc_btnNewButton.fill = GridBagConstraints.HORIZONTAL;
		gbc_btnNewButton.insets = new Insets(0, 0, 0, 5);
		gbc_btnNewButton.gridx = 0;
		gbc_btnNewButton.gridy = 0;
		buttonPanel.add(btnNewButton, gbc_btnNewButton);

		Icon iconSwitch = new ImageIcon("src/pictures/zurMonatsAnsicht.png");
		btnNewButton_1 = new JButton(iconSwitch);
		btnNewButton_1.setToolTipText(monatsansicht[speak]);
		btnNewButton_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				mainInstance.setProgressBarVisibleTrue();
				mainInstance.getTabbedPane().removeTabAt(0);
				mainInstance.setKalender(new CalView(mainInstance, clickedDay));
				mainInstance.getTabbedPane().add(mainInstance.getKalender(),
						kalender[speak]);

				mainInstance.getTabbedPane().remove(mainInstance.getKontakte());
				mainInstance.setKontakte(new AddContactPane());
				mainInstance.getTabbedPane().add(mainInstance.getKontakte(),
						kontakte[speak]);

				mainInstance.getTabbedPane().remove(mainInstance.getToDo());
				mainInstance.setToDo(new ToDoPane());
				mainInstance.getTabbedPane().add(mainInstance.getToDo(),
						todo[speak]);

				mainInstance.getTabbedPane().remove(mainInstance.getViewMail());
				mainInstance.setViewMail(new ViewMail(mainInstance));
				mainInstance.getTabbedPane().add(mainInstance.getViewMail(),
						mail[speak]);
				mainInstance.setProgressBarVisibleFalse();
			}
		});
		btnNewButton_1.setPreferredSize(new Dimension(110, 40));
		btnNewButton_1.setMinimumSize(new Dimension(110, 40));
		btnNewButton_1.setMaximumSize(new Dimension(110, 40));
		GridBagConstraints gbc_btnNewButton_1 = new GridBagConstraints();
		gbc_btnNewButton_1.insets = new Insets(0, 0, 0, 5);
		gbc_btnNewButton_1.gridx = 1;
		gbc_btnNewButton_1.gridy = 0;
		buttonPanel.add(btnNewButton_1, gbc_btnNewButton_1);

		btnNewButton_2 = new JButton("New button");
		btnNewButton_2.setVisible(false);
		btnNewButton_2.setPreferredSize(new Dimension(40, 40));
		btnNewButton_2.setMinimumSize(new Dimension(40, 40));
		btnNewButton_2.setMaximumSize(new Dimension(40, 40));
		GridBagConstraints gbc_btnNewButton_2 = new GridBagConstraints();
		gbc_btnNewButton_2.insets = new Insets(0, 0, 0, 5);
		gbc_btnNewButton_2.gridx = 2;
		gbc_btnNewButton_2.gridy = 0;
		buttonPanel.add(btnNewButton_2, gbc_btnNewButton_2);

		Icon iconLast = new ImageIcon("src/pictures/last.png");
		btnNewButton_3 = new JButton(iconLast);
		btnNewButton_3.setToolTipText(toolTipLM[speak]);
		btnNewButton_3.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				mainInstance.setProgressBarVisibleTrue();
				setClickedDay(cal.WeekData.getLastMonday(getClickedDay()));
				weekPanelScrollPane.setViewportView(null);
				createWeekView();
				wochenInfoTextField.setText(cal.WeekData
						.getWeekString(clickedDay));
				weekPanelScrollPane.setViewportView(weekPanel);
				mainInstance.setProgressBarVisibleFalse();
			}
		});
		btnNewButton_3.setPreferredSize(new Dimension(40, 40));
		btnNewButton_3.setMinimumSize(new Dimension(40, 40));
		btnNewButton_3.setMaximumSize(new Dimension(40, 40));
		GridBagConstraints gbc_btnNewButton_3 = new GridBagConstraints();
		gbc_btnNewButton_3.insets = new Insets(0, 0, 0, 5);
		gbc_btnNewButton_3.gridx = 3;
		gbc_btnNewButton_3.gridy = 0;
		buttonPanel.add(btnNewButton_3, gbc_btnNewButton_3);

		wochenInfoTextField = new JTextField();
		wochenInfoTextField.setToolTipText(toolTipAM[speak]);
		GridBagConstraints gbc_textField = new GridBagConstraints();
		gbc_textField.insets = new Insets(0, 0, 0, 5);
		gbc_textField.fill = GridBagConstraints.HORIZONTAL;
		gbc_textField.gridx = 4;
		gbc_textField.gridy = 0;
		wochenInfoTextField.setColumns(10);
		wochenInfoTextField.setText(cal.WeekData.getWeekString(d));
		wochenInfoTextField.setHorizontalAlignment(SwingConstants.CENTER);
		wochenInfoTextField.setToolTipText(toolTipAM[speak]);
		wochenInfoTextField.setDisabledTextColor(new Color(0, 0, 0));
		wochenInfoTextField.setEnabled(false);
		wochenInfoTextField.setEditable(false);
		buttonPanel.add(wochenInfoTextField, gbc_textField);

		Icon iconNext = new ImageIcon("src/pictures/next.png");
		btnNewButton_4 = new JButton(iconNext);
		btnNewButton_4.setToolTipText(toolTipNM[speak]);
		btnNewButton_4.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				mainInstance.setProgressBarVisibleTrue();
				setClickedDay(cal.WeekData.getNextMonday(getClickedDay()));
				weekPanelScrollPane.setViewportView(null);
				createWeekView();
				wochenInfoTextField.setText(cal.WeekData
						.getWeekString(clickedDay));
				weekPanelScrollPane.setViewportView(weekPanel);
				mainInstance.setProgressBarVisibleFalse();
			}
		});
		btnNewButton_4.setMaximumSize(new Dimension(40, 40));
		btnNewButton_4.setMinimumSize(new Dimension(40, 40));
		btnNewButton_4.setPreferredSize(new Dimension(40, 40));
		GridBagConstraints gbc_btnNewButton_4 = new GridBagConstraints();
		gbc_btnNewButton_4.gridx = 5;
		gbc_btnNewButton_4.gridy = 0;
		buttonPanel.add(btnNewButton_4, gbc_btnNewButton_4);

		// Ende-Button-Panel---------------------------------------------------------

		weekPanel = new JPanel();
		weekPanelScrollPane = new JScrollPane(weekPanel);
		add(weekPanelScrollPane);
		weekPanel.setLayout(new GridLayout(1, 0, 0, 0));

		createWeekView();

	}

	/**
	 * Erzeugt Wochenansicht neu
	 */
	@SuppressWarnings({ "unchecked", "static-access" })
	public void createWeekView() {// TODO
		weekPanel.removeAll();
		Date[] dates = cal.WeekData.getDateArray(clickedDay);
		String[] stringes = cal.WeekData.getStringArray(clickedDay, speak);

		for (int i = 0; i < dates.length; i++) {

			// Initialisierung
			final WeekDayPanel panel = new WeekDayPanel();
			List<Event> eventList = new ArrayList<Event>();
			List<String[]> gebList = new ArrayList<String[]>();
			List<MyTask> taskList = new ArrayList<MyTask>();

			// Setting Panel data
			panel.setDate(dates[i]);

			try {
				eventList = es.getTasks(es.getResultSet(), panel.getDate());
			} catch (NumberFormatException e1) {
				e1.printStackTrace();
			} catch (SQLException e1) {
				e1.printStackTrace();
			} catch (ParseException e1) {
				e1.printStackTrace();
			}

			try {
				taskList = ts.getTasks(ts.getResultSet(), panel.getDate());

			} catch (NumberFormatException e2) {
				e2.printStackTrace();
			} catch (SQLException e2) {
				e2.printStackTrace();
			}

			try {
				gebList = ps.getTasks(ps.getResultSet(), panel.getDate());

			} catch (NumberFormatException e) {
				e.printStackTrace();
			} catch (SQLException e) {
				e.printStackTrace();
			}

			panel.getAllCalendarItems().addAll(eventList);
			panel.getAllCalendarItems().addAll(taskList);
			panel.getAllCalendarItems().addAll(gebList);

			// TODO
			if (panel.getDate().equals(getClickedDay())) {
				setAllCalendarItems(panel.getAllCalendarItems());
				System.out.println("schleife geamcht");
			}

			// Naming Day
			panel.getDayNameLabel().setText(stringes[i]);

			// Adding Birthdays
			for (int j = 0; j < panel.getAllCalendarItems().size(); j++) {
				if (panel.getAllCalendarItems().get(j) instanceof String[]) {

					String[] temp = (String[]) panel.getAllCalendarItems().get(
							j);
					JLabel label = new JLabel();
					label.setPreferredSize(new Dimension(130, 50));
					label.setMaximumSize(new Dimension(130, 50));
					label.setMinimumSize(new Dimension(130, 50));
					label.setBackground(new Color(255, 255, 204));
					label.setVerticalAlignment(SwingConstants.TOP);
					label.setText("<html> <head></head><body style=\"background-color:rgb(255,255,204)\">"
							+ temp[0]
							+ " "
							+ temp[1]
							+ "<br />"
							+ " ("
							+ temp[2] + jahreKlammer[speak] + "</body></html>");
					panel.add(label);
				}

			}

			// Adding Tasks 205, 205, 193

			for (int j = 0; j < panel.getAllCalendarItems().size(); j++) {
				if (panel.getAllCalendarItems().get(j) instanceof MyTask) {
					MyTask temp = (MyTask) panel.getAllCalendarItems().get(j);
					JLabel label = new JLabel();
					label.setPreferredSize(new Dimension(130, 50));
					label.setVerticalAlignment(SwingConstants.TOP);
					label.setText(temp.weekToString());
					panel.add(label);
				}
			}

			// Adding Events
			for (int j = 0; j < panel.getAllCalendarItems().size(); j++) {
				if (panel.getAllCalendarItems().get(j) instanceof Event) {
					Event temp = (Event) panel.getAllCalendarItems().get(j);
					JLabel label = new JLabel();
					label.setPreferredSize(new Dimension(130, 50));
					label.setVerticalAlignment(SwingConstants.TOP);
					label.setText(temp.toString());
					panel.add(label);
				}
			}
			// Umrahmung des aktiven Panels
			if (panel.getDate().equals(getClickedDay())) {
				panel.setBorder(BorderFactory.createLineBorder(Color.black, 4));
			}

			// Adding MouseListener
			panel.addMouseListener(new MouseAdapter() {
				public void mouseClicked(MouseEvent arg0) {
					if (panel.getDate().equals(clickedDay)) {
						new DayView(getOwnInstance(), panel).setVisible(true);
					}
					clickedAction(panel);

				}
			});

			// Adding Button Funktion
			panel.getNewEventButton().addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent arg0) {
					new NewEventWindow(panel.getDate(), getOwnInstance())
							.setVisible(true);

				}

			});

			if (counter < panel.getAllCalendarItems().size()) {
				counter = panel.getAllCalendarItems().size();
			}

			// Adding Panel
			weekPanel.add(panel);
			weekPanel
					.setPreferredSize(new Dimension(130, ((counter + 1) * 55)));

		}
		counter = 0;
	}

	/**
	 * Erzeugt ProgressBar
	 * 
	 * @param panel
	 */
	public void clickedAction(WeekDayPanel panel) {
		mainInstance.setProgressBarVisibleTrue();
		setClickedDay(panel.getDate());
		weekPanelScrollPane.setViewportView(null);
		createWeekView();
		weekPanelScrollPane.setViewportView(weekPanel);
		mainInstance.setProgressBarVisibleFalse();
	}

	public WeekView getOwnInstance() {
		return ownInstance;
	}

	public void setOwnInstance(WeekView ownInstance) {
		this.ownInstance = ownInstance;
	}

	@SuppressWarnings("rawtypes")
	public List getAllCalendarItems() {
		return allCalendarItems;
	}

	public void setAllCalendarItems(
			@SuppressWarnings("rawtypes") List allCalendarItems) {
		this.allCalendarItems = allCalendarItems;
	}

	public Date getClickedDay() {
		return clickedDay;
	}

	public void setClickedDay(Date clickedDay) {
		this.clickedDay = clickedDay;
	}

	public Test getMainInstance() {
		return mainInstance;
	}

	public void setMainInstance(Test mainInstance) {
		this.mainInstance = mainInstance;
	}

	public JPanel getWeekPanel() {
		return weekPanel;
	}

	public void setWeekPanel(JPanel weekPanel) {
		this.weekPanel = weekPanel;
	}

	public TaskSet getTs() {
		return ts;
	}

	public void setTs() {
		this.ts = new TaskSet();
	}

	public EventSet getEs() {
		return es;
	}

	public void setEs() {
		this.es = new EventSet();
	}

	public Image resize(Image ret, int w, int h) {

		BufferedImage tmp = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
		Graphics2D g2 = tmp.createGraphics();
		g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
				RenderingHints.VALUE_INTERPOLATION_BILINEAR);
		g2.drawImage(ret, 0, 0, w, h, null);
		g2.dispose();
		return tmp;
	}

}
